<template>
	<el-dialog
		v-model="dialogVisible"
		class="le-dialog"
		:title="curTitle"
		:width="[1, 5].indexOf(type) !== -1 ? 680 : 460"
		destroy-on-close
		append-to-body
		@closed="$emit('closed')"
	>
		<template v-if="type === 1">
			<div class="sc-user-select">
				<div class="sc-user-select__left">
					<div class="sc-user-select__search">
						<el-input v-model="username" prefix-icon="Search" placeholder="搜索成员">
							<template #append>
								<el-button icon="Search" @click="search"></el-button>
							</template>
						</el-input>
					</div>
					<div class="sc-user-select__select">
						<div v-loading="showGrouploading" class="sc-user-select__tree">
							<el-scrollbar>
								<el-tree
									ref="groupTree"
									class="menu"
									:data="group"
									:node-key="groupProps.key"
									:props="groupProps"
									highlight-current
									:expand-on-click-node="false"
									:current-node-key="groupId"
									@node-click="groupClick"
								/>
							</el-scrollbar>
						</div>
						<div v-loading="showUserloading" class="sc-user-select__user">
							<div class="sc-user-select__user__list">
								<el-scrollbar ref="userScrollbar">
									<el-tree
										ref="userTree"
										class="menu"
										:data="user"
										:node-key="userProps.key"
										:props="userProps"
										:default-checked-keys="selectedIds"
										show-checkbox
										check-on-click-node
										@check-change="userClick"
									></el-tree>
								</el-scrollbar>
							</div>
							<footer>
								<el-pagination
									v-model:currentPage="currentPage"
									background
									layout="prev,next"
									small
									:total="total"
									:page-size="pageSize"
									@current-change="paginationChange"
								></el-pagination>
							</footer>
						</div>
					</div>
				</div>
				<div class="sc-user-select__toicon">
					<el-icon><arrow-right /></el-icon>
				</div>
				<div class="sc-user-select__selected">
					<header>已选 ({{ selected.length }})</header>
					<ul style="margin: 0; padding: 0">
						<el-scrollbar>
							<li v-for="(item, index) in selected" :key="item.id">
								<span class="name">
									<el-avatar size="small">{{ item.name?.substring(0, 1) }}</el-avatar>
									<label>{{ item.name || '-' }}</label>
								</span>
								<span class="delete">
									<el-button type="danger" icon="Delete" circle size="small" @click="deleteSelected(index)" />
								</span>
							</li>
						</el-scrollbar>
					</ul>
				</div>
			</div>
		</template>

		<template v-if="type === 3">
			<div class="sc-user-select sc-user-select-role">
				<div class="sc-user-select__left">
					<div class="sc-user-select__select">
						<div v-loading="showGrouploading" class="sc-user-select__tree">
							<el-scrollbar>
								<el-tree
									ref="groupTree"
									class="menu"
									:data="role"
									:node-key="roleProps.key"
									:props="roleProps"
									show-checkbox
									check-strictly
									check-on-click-node
									:expand-on-click-node="false"
									:default-checked-keys="selectedIds"
									@check-change="roleClick"
								/>
							</el-scrollbar>
						</div>
					</div>
				</div>
				<div class="sc-user-select__toicon">
					<el-icon><ArrowRight /></el-icon>
				</div>
				<div class="sc-user-select__selected">
					<header>已选 ({{ selected.length }})</header>
					<ul style="padding: 0; margin: 0">
						<el-scrollbar>
							<li v-for="(item, index) in selected" :key="item.id">
								<span class="name">
									<label>{{ item.name || '-' }}</label>
								</span>
								<span class="delete">
									<el-button type="danger" icon="Delete" circle size="small" @click="deleteSelected(index)" />
								</span>
							</li>
						</el-scrollbar>
					</ul>
				</div>
			</div>
		</template>

		<template v-if="type === 5">
			<div class="sc-user-select">
				<div class="sc-user-select__left">
					<div class="sc-user-select__search">
						<el-input v-model="keyword" prefix-icon="Search" placeholder="搜索表单">
							<template #append>
								<el-button icon="Search" @click="searchTemplate"></el-button>
							</template>
						</el-input>
					</div>
					<div class="sc-user-select__select">
						<div class="sc-user-select__tree">
							<el-scrollbar>
								<el-tree
									ref="formCategoryTreeRef"
									class="menu"
									:data="formCategoryTree"
									:node-key="formCategoryProps.key"
									:props="formCategoryProps"
									highlight-current
									:expand-on-click-node="false"
									:current-node-key="formCategoryId"
									@node-click="formCategoryClick"
								/>
							</el-scrollbar>
						</div>
						<div class="sc-user-select__user">
							<div class="sc-user-select__user__list">
								<el-scrollbar ref="formTemplateScrollbar">
									<el-tree
										ref="formTemplateTree"
										class="menu"
										:data="formTemplate"
										:node-key="formTemplateProps.key"
										:props="formTemplateProps"
										:default-checked-keys="selectedIds"
										show-checkbox
										check-on-click-node
										@check-change="formTemplateClick"
									></el-tree>
								</el-scrollbar>
							</div>
							<footer>
								<el-pagination
									v-model:currentPage="currentPage"
									background
									layout="prev,next"
									small
									:total="total"
									:page-size="pageSize"
									@current-change="paginationChange"
								></el-pagination>
							</footer>
						</div>
					</div>
				</div>
				<div class="sc-user-select__toicon">
					<el-icon><arrow-right /></el-icon>
				</div>
				<div class="sc-user-select__selected">
					<header>已选 ({{ selected.length }})</header>
					<ul style="margin: 0; padding: 0">
						<el-scrollbar>
							<li v-for="(item, index) in selected" :key="item.id">
								<span class="name">
									<el-avatar size="small">{{ item.name?.substring(0, 1) }}</el-avatar>
									<label>{{ item.name || '-' }}</label>
								</span>
								<span class="delete">
									<el-button type="danger" icon="Delete" circle size="small" @click="deleteSelected(index)" />
								</span>
							</li>
						</el-scrollbar>
					</ul>
				</div>
			</div>
		</template>

		<template #footer>
			<el-button @click="dialogVisible = false">取 消</el-button>
			<el-button type="primary" @click="save">确 认</el-button>
		</template>
	</el-dialog>
</template>

<script>
import config from '@/config/workflow'
import department from '@/api/system/department'
import user from '@/api/system/user'
import role from '@/api/system/role'
import formCategory from '@/api/flow/formcategory'
import formtemplate from '@/api/flow/formtemplate'
import { ElMessage } from 'element-plus'

export default {
	props: {
		modelValue: { type: Boolean, default: false },
		minSelected: { type: Number, default: 0 },
		maxSelected: { type: Number, default: 999999 }
	},
	data() {
		return {
			groupProps: {
				key: 'id',
				label: 'name',
				children: 'children'
			},
			userProps: {
				key: 'id',
				label: 'realName'
			},
			roleProps: {
				key: 'id',
				label: 'name',
				children: 'children'
			},
			formCategoryProps: {
				key: 'id',
				label: 'name',
				children: 'children'
			},
			formTemplateProps: {
				key: 'id',
				label: 'name'
			},
			dialogVisible: false,
			showGrouploading: false,
			showUserloading: false,
			keyword: '',
      username: '',
			groupId: '',
			pageSize: config.user.pageSize,
			total: 0,
			currentPage: 1,
			group: [],
			user: [],

			role: [],
			type: 1, // 1: 用户 3: 角色 5: 子表单
			selected: [],
			value: [],

			// 表单分类
			formCategoryTree: [],
			formCategoryId: '',
			formTemplate: []
		}
	},
	computed: {
		selectedIds() {
			return this.selected.map(t => t.id)
		},
		curTitle() {
			return {
				1: '人员选择',
				3: '角色选择',
				5: '表单分类选择'
			}[this.type]
		}
	},
	mounted() {},
	methods: {
		//打开赋值
		open(type, data) {
			// 1: 用户 3: 角色 5: 子表单
			this.type = type
			this.value = JSON.parse(JSON.stringify(data || []))
			this.selected = JSON.parse(JSON.stringify(data || []))
			this.dialogVisible = true

			if (this.type === 1) {
				this.getGroup()
				this.getUser()
			} else if (this.type === 3) {
				this.getRole()
			} else if (this.type === 5) {
				this.getFormCategoryListTreeListEv()
				this.getFormTemplateListEv()
			}
		},
		//获取组织
		async getGroup() {
			this.showGrouploading = true
			var res = await department.departmentPageApi({ page: 1, pageSize: 20 })
			this.showGrouploading = false
			var allNode = { id: '', name: '所有' }
			res.unshift(allNode)
			this.group = res
		},
		//获取用户
		async getUser() {
			this.showUserloading = true
			var params = {
				data: {
					username: this.username || null,
					departmentId: this.groupId || null
				},
				page: this.currentPage,
				pageSize: this.pageSize
			}
			var res = await user.userPageApi(params)
			this.showUserloading = false
			this.user = res.records
			this.total = res.total || 0
			this.$refs.userScrollbar.setScrollTop(0)
		},
		//获取角色
		async getRole() {
			this.showGrouploading = true
			var res = await role.rolePageApi({ page: 1, pageSize: 999 })
			this.showGrouploading = false
			this.role = res?.records
		},
		//组织点击
		groupClick(data) {
			this.keyword = ''
			this.currentPage = 1
			this.groupId = data.id
			this.getUser()
		},
		//用户点击
		userClick(data, checked) {
			if (checked) {
				this.selected.push({
					id: data.id,
					name: data.realName
				})
			} else {
				this.selected = this.selected.filter(item => item.id != data.id)
			}
		},
		//表单模板点击
		formTemplateClick(data, checked) {
			if (checked) {
				this.selected.push({
					id: data.id,
					name: data.name
				})
			} else {
				this.selected = this.selected.filter(item => item.id != data.id)
			}
		},
		//用户分页点击
		paginationChange() {
			if (this.type === 1) {
				this.getUser()
			} else if (this.type === 5) {
				this.getFormTemplateListEv()
			}
		},
		//用户搜索
		search() {
			this.groupId = ''
			this.$refs.groupTree.setCurrentKey(this.groupId)
			this.currentPage = 1
			this.getUser()
		},
		// 表单模板搜索
		searchTemplate() {
			this.formCategoryId = ''
			this.$refs.formCategoryTreeRef.setCurrentKey(this.formCategoryId)
			this.currentPage = 1
			this.getFormTemplateListEv()
		},
		//删除已选
		deleteSelected(index) {
			this.selected.splice(index, 1)
			if (this.type === 1) {
				this.$refs.userTree.setCheckedKeys(this.selectedIds)
			} else if (this.type === 3) {
				this.$refs.groupTree.setCheckedKeys(this.selectedIds)
			} else if (this.type === 5) {
				this.$refs.formTemplateTree.setCheckedKeys(this.selectedIds)
			}
		},
		//角色点击
		roleClick(data, checked) {
			if (checked) {
				this.selected.push({
					id: data.id,
					name: data.name
				})
			} else {
				this.selected = this.selected.filter(item => item.id != data.id)
			}
		},
		//提交保存
		save() {
			this.value.splice(0, this.value.length)
			this.selected.map(item => {
				this.value.push(item)
			})
			// 最小限制
			const minSelected = this.minSelected
			// 最大限制
			const maxSelected = this.type === 5 ? 1 : this.maxSelected
			const selected_l = this.selected.length
			if (selected_l < minSelected) {
				return this.$message.warning(`选中的数据个数不能小于${minSelected}条`)
			}
			if (selected_l > maxSelected) {
				return this.$message.warning(`选中的数据个数不能大于${maxSelected}条`)
			}
			this.$emit('update:selected', this.value)
			this.dialogVisible = false
		},
		// 获取表单分类树结构
		async getFormCategoryListTreeListEv() {
			let data = await formCategory.formCategoryListTreeApi({})
			this.formCategoryTree = [{ id: '', name: '所有', children: data }]
		},
		// 分类点击
		formCategoryClick(data) {
			this.keyword = ''
			this.currentPage = 1
			this.formCategoryId = data.id
			this.getFormTemplateListEv()
		},
		// 获取表单分类下的表单模板
		async getFormTemplateListEv() {
			var params = {
				data: {
					name: this.keyword || null,
					formCategoryId: this.formCategoryId || null
				},
				page: this.currentPage,
				pageSize: this.pageSize
			}
			const data = await formtemplate.formTemplateSimpleListApi(params)
			this.formTemplate = data.records
			this.total = data.total || 0
			this.$refs.formTemplateScrollbar.setScrollTop(0)
		}
	}
}
</script>

<style scoped>
.sc-user-select {
	display: flex;
}
.sc-user-select__left {
	width: 400px;
}
.sc-user-select__right {
	flex: 1;
}

.sc-user-select__search {
	padding-bottom: 10px;
}

.sc-user-select__select {
	display: flex;
	border: 1px solid var(--el-border-color-light);
	background: var(--el-color-white);
}
.sc-user-select__tree {
	width: 200px;
	height: 300px;
	border-right: 1px solid var(--el-border-color-light);
}
.sc-user-select__user {
	width: 200px;
	height: 300px;
	display: flex;
	flex-direction: column;
}
.sc-user-select__user__list {
	flex: 1;
	overflow: auto;
}
.sc-user-select__user footer {
	height: 36px;
	padding-top: 5px;
	border-top: 1px solid var(--el-border-color-light);
}

.sc-user-select__toicon {
	display: flex;
	justify-content: center;
	align-items: center;
	margin: 0 10px;
}
.sc-user-select__toicon i {
	display: flex;
	justify-content: center;
	align-items: center;
	background: #ccc;
	width: 20px;
	height: 20px;
	text-align: center;
	line-height: 20px;
	border-radius: 50%;
	color: #fff;
}

.sc-user-select__selected {
	height: 345px;
	width: 200px;
	border: 1px solid var(--el-border-color-light);
	background: var(--el-color-white);
}
.sc-user-select__selected header {
	height: 43px;
	line-height: 43px;
	border-bottom: 1px solid var(--el-border-color-light);
	padding: 0 15px;
	font-size: 12px;
}
.sc-user-select__selected ul {
	height: 300px;
	overflow: auto;
}
.sc-user-select__selected li {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 5px 5px 5px 15px;
	height: 38px;
}
.sc-user-select__selected li .name {
	display: flex;
	align-items: center;
}
.sc-user-select__selected li .name .el-avatar {
	background: var(--el-color-primary);
	margin-right: 10px;
}
.sc-user-select__selected li .name label {
}
.sc-user-select__selected li .delete {
	display: none;
}
.sc-user-select__selected li:hover {
	background: var(--el-color-primary-light-9);
}
.sc-user-select__selected li:hover .delete {
	display: inline-block;
}

.sc-user-select-role .sc-user-select__left {
	width: 200px;
}
.sc-user-select-role .sc-user-select__tree {
	border: none;
	height: 343px;
}
.sc-user-select-role .sc-user-select__selected {
}

[data-theme='dark'] .sc-user-select__selected li:hover {
	background: rgba(0, 0, 0, 0.2);
}
[data-theme='dark'] .sc-user-select__toicon i {
	background: #383838;
}
</style>
